/**
 * 
 */
package br.com.unifebe.tcc.componente.GUI;

import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.Arrays;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;

import br.com.unifebe.tcc.componente.GUI.GUIUtils.ShowCaseType;
import br.com.unifebe.tcc.componente.GUI.GUIUtils.Tipos;
/**
 * @Autor Carlos
 *
 */
public class JMLPasswordEdit extends JPasswordField implements IControlable {
	private int maxlength=0;
	private ShowCaseType showcase=ShowCaseType.FREE_CASE;
	private JLabel msgLabel;
	private boolean isKey=false;
	private Tipos tipo_dado = Tipos.STRING;
	private char[] acepted_keys;
	private String atributo;
	private String valorPadrao;
	private Object definindoTexto = new Object();
	
	/**
	 * Edit com algumas propriedades modificadas
	 * ColorOnFocus();
	 * MaxLength();
	 */
	
	
	public JMLPasswordEdit() {
		this(null,0);
	}
	
	public JMLPasswordEdit(int tamanhoTexto) {
		this(null,tamanhoTexto);
	}
	
	public JMLPasswordEdit(JLabel msgLabel,int tamanhoTexto) {
		super(tamanhoTexto);
		this.setFont(Parametros.getFontEdit());
		setMaxLength(tamanhoTexto);
		this.msgLabel = msgLabel;
		init();
	}
	
	private void init() {
		FormataEdit();
		this.setBackground(Parametros.getCorEdit());
		this.setFont(Parametros.getFontEdit());
		this.setForeground(Parametros.getCorFontEdit());
		
		this.addFocusListener(new java.awt.event.FocusListener() {
			@Override
			public void focusGained(java.awt.event.FocusEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						JMLPasswordEdit.this.setBackground(Parametros.getCorEditSelecionado());
						JMLPasswordEdit.this.setFont(Parametros.getFontEditSelecionado());
						JMLPasswordEdit.this.setForeground(Parametros.getCorFontEditSelecionado());
						JMLPasswordEdit.this.selectAll();
						if (JMLPasswordEdit.this.msgLabel!=null) {
							JMLPasswordEdit.this.msgLabel.setText(JMLPasswordEdit.this.getToolTipText());
						}
					}
				});
			}
			@Override
			public void focusLost(java.awt.event.FocusEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						JMLPasswordEdit.this.setBackground(Parametros.getCorEdit());
						JMLPasswordEdit.this.setFont(Parametros.getFontEdit());
						JMLPasswordEdit.this.setForeground(Parametros.getCorFontEdit());
						if (JMLPasswordEdit.this.msgLabel!=null) {
							JMLPasswordEdit.this.msgLabel.setText("");
						}
					}
				});
			}
		});

		this.addKeyListener(new java.awt.event.KeyAdapter() {
			@Override
			public void keyTyped(java.awt.event.KeyEvent e) {
				
				if (! tipo_dado.equals(Tipos.STRING)) {
					if (acepted_keys!=null && !acepted_keys.equals("") 
							&& Arrays.binarySearch(acepted_keys, e.getKeyChar()) < 0) {
						
						e.setKeyChar((char)KeyEvent.VK_CLEAR);
					
					} else {
						if (getShowCase()==ShowCaseType.UPPER_CASE) {
							e.setKeyChar(Character.toUpperCase(e.getKeyChar()));
						}
						if (getShowCase()==ShowCaseType.LOWER_CASE) {
							e.setKeyChar(Character.toUpperCase(e.getKeyChar()));
						}
						if ((getText().length()>=getMaxLength()) &&
						   (getMaxLength()>0)) {
							e.setKeyChar((char)KeyEvent.VK_CLEAR);
						}
					}
				} else {
					if (getShowCase()==ShowCaseType.UPPER_CASE) {
						e.setKeyChar(Character.toUpperCase(e.getKeyChar()));
					}
					if (getShowCase()==ShowCaseType.LOWER_CASE) {
						e.setKeyChar(Character.toUpperCase(e.getKeyChar()));
					}
					if ((getText().length()>=getMaxLength()) &&
					   (getMaxLength()>0)) {
						e.setKeyChar((char)KeyEvent.VK_CLEAR);
					}
				}
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == 10 ) {
					JComponent comp = ( (JComponent) GUIUtils.findNextFocus() ); 
					if (comp != null) {
						comp.grabFocus();
					}
				}
			}
			
		});
	}

	public int getMaxLength() {
		return maxlength;
	}
	
	public void setMaxLength(int length) {
		this.maxlength = length;
	}
	
	public void setShowCase(ShowCaseType showcase) {
		this.showcase = showcase;
	}
	
	public ShowCaseType getShowCase() {
		return this.showcase;
	}
	
	public void setMsgLabel(JLabel label) {
		this.msgLabel = label;
	}
	public JLabel getMsgLabel() {
		return this.msgLabel;
	}
	
	public boolean isKey() {
		return this.isKey;
	}
	
	public void setKey(boolean b) {
		this.isKey = b;
	}
	
	public void setTipo(Tipos tipo) {
		this.tipo_dado = tipo;
		FormataEdit();
	}

	public Tipos getTipo() {
		return this.tipo_dado;
	}
	
	private void FormataEdit() {
		switch (tipo_dado) {
			case DATE:
				{
					this.setHorizontalAlignment(SwingConstants.LEFT);
					this.setText("");
					this.acepted_keys = Parametros.getNumerosInteirosLiberados();
					Arrays.sort(acepted_keys);
					break;
				}
			case INTEGER:
				{
					this.setHorizontalAlignment(SwingConstants.RIGHT);
					this.setText("0");
					this.acepted_keys = Parametros.getNumerosInteirosLiberados();
					Arrays.sort(acepted_keys);
					break;
				}
			case LONG:
				{
					this.setHorizontalAlignment(SwingConstants.RIGHT);
					this.setText("0");
					this.acepted_keys = Parametros.getNumerosInteirosLiberados();
					Arrays.sort(acepted_keys);
					break;
				}
			case FLOAT:
				{
					this.setHorizontalAlignment(SwingConstants.RIGHT);
					this.acepted_keys = Parametros.getNumerosFloatsLiberados();
					Arrays.sort(acepted_keys);
					this.setText("0");
					break;
				}
			case STRING: 
				{
					this.setHorizontalAlignment(SwingConstants.LEFT);
					this.setText("");
					this.acepted_keys = Parametros.getCharsLiberados();
					Arrays.sort(acepted_keys);
					break;
				}
			default:
				break;
		}
	}




	/**
	 * @return the atributo
	 */
	public String getAtributo() {
		return atributo;
	}


	/**
	 * @param atributo the atributo to set
	 */
	public void setAtributo(String atributo) {
		this.atributo = atributo;
	}
	
	

//	public Component findNextFocus() {
//		GUIUtils.findNextFocus();
////      //   Find focus owner
////        Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
////        Container root = c == null ? null : c.getFocusCycleRootAncestor();
////    
////        if (root != null) {
////            FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
////            Component nextFocus = policy.getComponentAfter(root, c);
////            if (nextFocus == null) {
////                nextFocus = policy.getDefaultComponent(root);
////            }
////            return nextFocus;
////        }
//        return null;
//    }
	
	@Override
	public String getText() {
		
		String result = "";

		synchronized (definindoTexto) {
			result = super.getText();
		    if (tipo_dado==Tipos.FLOAT || tipo_dado==Tipos.INTEGER || tipo_dado==Tipos.LONG) {
		    	if (result == null || result.equals("")) {
		    		result = "0";
		    	}
		    }
		}
		
		return result;
	}
	
	public Long getLong() {
		String t = getText();
		return Long.parseLong( ( t==null || t.isEmpty() ? "0" : t ) );
	}

	public Double getDouble() {
		return Double.parseDouble(getText());
	}

	public Integer getInteger() {
		return Integer.parseInt(getText());
	}

	@Override
	public void setText(String t) {
		synchronized (definindoTexto) {
			if (t==null) {
				t = "";
			}
			final String texto = t;
			try {
	//			SwingUtilities.invokeLater(new Runnable() {
	//				public void run() {
						JMLPasswordEdit.super.setText( texto );
	//				}
	//			});			
			} catch (Exception e) {
				e.printStackTrace();
				Logger.getLogger( getClass() ).error( e );
			}
		}
	}
	
	
	public void setText(Long l) {
		if (l==null) {
			l = 0l;
		}
		this.setText(String.valueOf(l));
	}
	
	public void setText(Integer l) {
		if (l==null) {
			l = 0;
		}
		this.setText(String.valueOf(l));
	}
	
	public void setText(Double d) {
		if (d==null) {
			d = 0d;
		}
		this.setText(String.valueOf(d));
	}
	
	public void setText(BigDecimal b) {
		if (b==null) {
			b = new BigDecimal("0");
		}
		this.setText(String.valueOf(b.doubleValue()));
	}
	
	@Override
	public void reset() {
		this.setText(getValorPadrao());
	}
	
	public String getValorPadrao() {
		return valorPadrao;
	}
	
	public void setValorPadrao(String valorPadrao) {
		this.valorPadrao = valorPadrao;
	}
	
	@Override
	public Object getUserObject() {
		if (tipo_dado==Tipos.INTEGER) {
			return getInteger();
		} else if (tipo_dado==Tipos.FLOAT) {
			return new BigDecimal( getText() );
		} else if (tipo_dado==Tipos.LONG) {
			return getLong();
		} else {
			return getText();
		}
	}
	
	@Override
	public void setUserObject(Object object) {
		if (object instanceof Long) {
			setText( (Long)object );
		} else if (object instanceof Double) {
			setText( (Long)object );
		} else if (object instanceof Integer) {
			setText( (Integer)object );
		} else if (object instanceof BigDecimal) {
			setText( (BigDecimal)object );
		} else {
			setText( String.valueOf( object ));
		}
		
	}
	
	@Override
	public boolean isEnabledControl() {
		return isEnabled();
	}
	@Override
	public void setEnabledControl(boolean b) {
		setEnabled( b );
	}
	@Override
	public void initializing(boolean state) {
		// TODO Auto-generated method stub
		
	}}
